package com.niguang.labour.common.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 */
@Slf4j
@Component
public class ApiTokenUtils {


    private final static String key = "877529a1b1f59c04a15b33ba41e487d7";

    // 一周过期
    private final static Long expiration = 864000L;

    /**
     * 创建新token
     *
     * @param userId 用户编号
     * @return token 令牌
     */
    public static String createNewToken(Long userId, Long laborId) {

        Date currentTime = new Date(System.currentTimeMillis());
        // 超时时间
        Date timeout = new Date(currentTime.getTime() + expiration * 1000);

        Map<String, Object> claims = new HashMap<>();
        claims.put("laborId", laborId);
        claims.put("userId", userId);
        return Jwts.builder().setSubject(userId.toString())
                .setClaims(claims)
                .setIssuedAt(currentTime).setIssuer("KuMing NiGuang Science technology Co.").setExpiration(timeout)
                .signWith(SignatureAlgorithm.HS256, key).compact();
    }


    /**
     * 通过令牌解析出userId
     *
     * @param token 令牌
     * @return userId 用户编号
     */
    public Long getUserIdByToken(String token) {
        //return Long.valueOf(Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject());
        return Long.valueOf(Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().get("userId").toString());
    }


    /**
     * 通过令牌解析出userId
     *
     * @return userId 用户编号
     */
    public Long getUserId() {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        final String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return getUserIdByToken(token);
    }


    /**
     * 通过令牌解析出userId
     *
     * @return userId 用户编号
     */
    public Long getLaborId() {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        final String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return Long.valueOf(Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().get("laborId").toString());
    }


    public static void main(String[] args) {
        // Date currentTime = new Date(System.currentTimeMillis());
        // System.out.println(currentTime.getTime());
        String newToken = createNewToken(111112255L, 1L);
        //  System.out.println("Authorization:" + newToken);
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJLdU1pbmcgTmlHdWFuZyBTY2llbmNlIHRlY2hub2xvZ3kgQ28uIiwibGFib3JJZCI6MSwiZXhwIjoxNTM3NDk1NzYyLCJpYXQiOjE1MzY2MzE3NjJ9.XQnxnwLbYIId1fTVlNSYwFO5u4fp2YunTS_9wSABkAo";
//        Long aLong = Long.valueOf(Jwts.parser().setSigningKey("877529a1b1f59c04a15b33ba41e487d7").parseClaimsJws(token).getBody().getSubject());
        String subject = Jwts.parser().setSigningKey(key).parseClaimsJws(newToken).getBody().get("userId").toString();
        System.out.println(subject);
        Long laborId = Long.valueOf(Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().get("laborId").toString());
        System.out.println(laborId);
    }
}
